mod utils;

use clap::{Parser, Subcommand};
use pan123_core::PanClient;

// 1. 定义命令行结构
#[derive(Parser)]
#[command(name = "123-cli")]
#[command(about = "123 Pan Command Line Interface", long_about = None)]
struct Cli {
    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand)]
enum Commands {
    /// 列出文件 文件夹id
    Info {
        /// 文件夹 ID 或 路径
        id: String,
    },

    /// 列出文件 文件夹id
    #[command(alias = "ls")]
    List {
        /// 文件夹 ID 或 路径
        id: String,

        /// 是否递归遍历文件夹
        #[arg(short, long)]
        recursive: bool,
    },

    /// 搜索文件
    Search {
        /// 搜索关键词
        query: String,

        /// 搜索目录
        #[arg(short, long)]
        dir: Option<String>,
    },

    /// 上传文件 (Upload file)
    #[command(alias = "up")]
    Upload {
        /// 本地文件路径
        source: String,
        /// 远程目标文件夹 ID
        target: String,
    },

    /// 删除文件（默认移动到回收站）
    #[command(alias = "rm")]
    Delete {
        /// 文件 ID 或 路径
        id: String,

        /// 是否彻底删除（默认 false，删除到回收站）
        #[arg(short, long)]
        permanent: bool,
    },

    /// 下载文件 (Download file)
    #[command(alias = "dl")]
    Download {
        /// 远程文件 ID
        id: String,
        /// 本地保存路径
        #[arg(short, long)]
        output: String,
    },

    /// 刷新直链缓存
    Refresh,
}

#[tokio::main]
async fn main() {
    let client_id = std::env::var("PAN123_CLIENT_ID").expect("Missing CLIENT_ID");
    let client_secret = std::env::var("PAN123_CLIENT_SECRET").expect("Missing CLIENT_SECRET");
    let client = PanClient::new(client_id, client_secret);
    if let Err(err) = run(&client).await {
        let error_obj = serde_json::json!({
            "err": 1,
            "message": err.to_string()
        });
        println!("{}", serde_json::to_string_pretty(&error_obj).unwrap());
    }
}

async fn run(client: &PanClient) -> anyhow::Result<()> {
    let cli = Cli::parse();

    match &cli.command {
        Commands::List { id, recursive } => {
            let id = id.parse::<i64>()?;
            if *recursive {
                // eprintln!("递归列出目录: {}", id);
                let resp = client.list_tree(id).await?;
                println!("{}", serde_json::to_string_pretty(&resp).unwrap());
            } else {
                let resp = client.list(id).await?;
                println!("{}", serde_json::to_string_pretty(&resp).unwrap());
            }
        }
        Commands::Upload { source, target } => {
            let id = target.parse::<i64>()?;
            let resp = client.upload(source, id, Some(2)).await?;
            println!("{}", serde_json::to_string_pretty(&resp).unwrap());
        }
        Commands::Download { id, output } => {
            // 需要配合列表获取文件id，才能下载文件
            eprintln!("下载文件 ID: {} 到 {:?}", id, output);
            // 下载逻辑...
        }
        Commands::Search { query, dir } => {
            let dir = dir.as_deref();
            let resp = client.search(query, dir).await?;
            println!("{}", serde_json::to_string_pretty(&resp).unwrap());
        }
        Commands::Delete { id, permanent } => {
            eprintln!("删除文件 ID: {} (永久删除: {})", id, permanent);
            // 删除逻辑...
        }
        Commands::Refresh => {
            eprintln!("刷新直链缓存");
            // 刷新逻辑...
        }
        Commands::Info { id } => {
            let resp = client.get_file_info(id.parse::<i64>()?).await?;
            println!("{}", serde_json::to_string_pretty(&resp).unwrap());
        }
    }

    Ok(())
}
